package source.backtrace;

import java.util.*;

public class NQueens {
    List<List<String>> solutions = new ArrayList<List<String>>(); // 结果集
    Set<Integer> columns = new HashSet<>(); // 记录皇后已占据的列
    Set<Integer> diagonals1 = new HashSet<>(); // 记录皇后已占据的主对角线 row - column 相等
    Set<Integer> diagonals2 = new HashSet<>(); // 记录皇后已占据的副对角线 row + column 相等

    public List<List<String>> solveNQueens(int n) {

        int[] queens = new int[n];
        Arrays.fill(queens, -1);

        backtrack(queens, n, 0);

        return solutions;
    }

    /**
     * 回溯
     *
     * @param queens 皇后位置
     * @param n      皇后数量
     * @param row    当前行
     */
    public void backtrack(int[] queens, int n, int row) {
        if (row == n)
            solutions.add(generateBoard(queens, n));
        else {
            for (int i = 0; i < n; i++) {
                if (columns.contains(i)) continue;
                int diagonal1 = row - i;
                if (diagonals1.contains(diagonal1)) continue;
                int diagonal2 = row + i;
                if (diagonals2.contains(diagonal2)) continue;

                queens[row] = i;
                columns.add(i);
                diagonals1.add(diagonal1);
                diagonals2.add(diagonal2);
                backtrack(queens, n, row + 1);
                columns.remove(i);
                diagonals1.remove(diagonal1);
                diagonals2.remove(diagonal2);
                queens[row] = -1;
            }
        }

    }

    public List<String> generateBoard(int[] queens, int n) {
        List<String> board = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            char[] row = new char[n];
            Arrays.fill(row, '.');
            row[queens[i]] = 'Q';
            board.add(new String(row));
        }
        return board;
    }
}
